package com.purong.purong.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.adapter.ArticleListAdapter;
import com.purong.purong.adapter.SearchTagAdapter;
import com.purong.purong.bean.ArticleBean;
import com.purong.purong.bean.ArticleHotTagBean;
import com.purong.purong.bean.ArticleListBean;
import com.purong.purong.util.ACache;
import com.purong.purong.widget.ConfirmDialog;
import com.purong.purong.widget.LoadingView;
import com.yao.sdk.net.ResponseInfo;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrCustomHandler;
import in.srain.cube.views.ptr.PtrDefaultCustomHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrPuRongLayout;

/**
 * Created by wenjiezeng on 2017/11/9.
 */
public class ArticleSearchActivity extends BaseActivity {
    private TagFlowLayout hotFlowLayout,hisFlowLayout;
    private SearchTagAdapter hotAdapter,hisAdapter;
    private ArrayList<String> hotTagList=new ArrayList<>();
    private ArrayList<String> hisTagList=new ArrayList<>();
    private EditText searchEd;
    private ImageView clear;
    private ACache mCache;
    private int page=1;
    private RecyclerView recyclerView;
    private PtrPuRongLayout mPtrFrame;
    private ArticleListAdapter mAdapter;
    private List<ArticleBean> articleList=new ArrayList<>();
    private String searchContent="";
    private ArticleListBean listBean;
    private LoadingView loadingView;
    @Override
    public int getRootViewId() {
        return R.layout.activity_article_search;
    }

    @Override
    public void initBundle() {
        mCache= ACache.get(this);
        hisTagList=(ArrayList<String>)mCache.getAsObject("SEARCH_ARTICLE_HISTORY");
        if (hisTagList==null)
            hisTagList=new ArrayList<>();
    }

    @Override
    public void initView() {

        hotFlowLayout=(TagFlowLayout)findViewById(R.id.hot_flowlayout);
        hisFlowLayout=(TagFlowLayout)findViewById(R.id.history_flowlayout);
        hotAdapter=new SearchTagAdapter(this,hotFlowLayout,hotTagList);
        hotAdapter.setOnTagClickListener(new SearchTagAdapter.OnTagClickListener() {
            @Override
            public void onTagClick(int position) {
                findViewById(R.id.tag_lay).setVisibility(View.GONE);
                findViewById(R.id.list_lay).setVisibility(View.VISIBLE);
                searchContent=hotTagList.get(position).trim();
                searchEd.setText(searchContent);
                searchArticle(true);
                addHistory();
            }
        });
        hotFlowLayout.setAdapter(hotAdapter);
        hisAdapter=new SearchTagAdapter(this,hisFlowLayout,hisTagList);
        hisAdapter.setOnTagClickListener(new SearchTagAdapter.OnTagClickListener() {
            @Override
            public void onTagClick(int position) {
                findViewById(R.id.tag_lay).setVisibility(View.GONE);
                findViewById(R.id.list_lay).setVisibility(View.VISIBLE);
                searchContent=hisTagList.get(position).trim();
                searchEd.setText(searchContent);
                searchArticle(true);
            }
        });
        hisFlowLayout.setAdapter(hisAdapter);
        if (hisTagList.size()>0){
            findViewById(R.id.history_lay).setVisibility(View.VISIBLE);
        }else {
            findViewById(R.id.history_lay).setVisibility(View.GONE);
        }
        clear=(ImageView)findViewById(R.id.clear);
        searchEd=(EditText)findViewById(R.id.search_ed);
        searchEd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
                if(arg1 == EditorInfo.IME_ACTION_SEARCH)
                {
                    if (arg0.getText().toString().trim().equals("")){
                        showToast("请输入搜索内容");
                    }else {
                        findViewById(R.id.tag_lay).setVisibility(View.GONE);
                        findViewById(R.id.list_lay).setVisibility(View.VISIBLE);
                        InputMethodManager imm=(InputMethodManager)searchEd.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0,InputMethodManager.SHOW_FORCED);
                        searchContent=arg0.getText().toString().trim();
                        searchArticle(true);
                        addHistory();
                    }

                }
                return false;
            }
        });
        searchEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().equals("")){
                    clear.setVisibility(View.GONE);
                    findViewById(R.id.tag_lay).setVisibility(View.VISIBLE);
                    findViewById(R.id.list_lay).setVisibility(View.GONE);
                    articleList.clear();
                    mAdapter.notifyDataSetChanged();
                }else {
                    clear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        loadingView=(LoadingView)findViewById(R.id.loading_view);
        loadingView.setNoResultToast("未找到符合条件的资讯","");
        loadingView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                searchArticle(true);
            }

            @Override
            public void onRefresh() {

            }
        });
        recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        mAdapter=new ArticleListAdapter(this);
        mAdapter.setData(articleList);
        mAdapter.setOnInfoItemClickListener(new ArticleListAdapter.OnArticleItemClickListener() {
            @Override
            public void onArticleClick(ArticleBean bean) {
                Intent intent=new Intent(ArticleSearchActivity.this, ArticleDetActivity.class);
                intent.putExtra("ARTICLE_ID",bean.getArticle_id());
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(mAdapter);
        mPtrFrame = (PtrPuRongLayout)findViewById(R.id.rotate_header_list_view_frame);
        mPtrFrame.setPtrHandler(new PtrCustomHandler() {
            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                if (articleList.size() == 0) {
                    return false;
                } else {
                    return PtrDefaultCustomHandler.checkContentCanBePulledUp(frame, content, footer);
                }

            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                searchArticle(false);

            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {

            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return false;
//                return PtrDefaultCustomHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
    }
    private void searchArticle(boolean clear){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("article_search",searchContent);
        if (clear){
            loadingView.loading();
            page=1;
            articleList.clear();
            mAdapter.notifyDataSetChanged();

        }
        params.put("page",page+"");
        if (!request(Contant.ARTICLE_SEARCH, params, true)) {
            if (clear){
                loadingView.fail();
            }
            if (!hasDestroy())
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        if (mPtrFrame.isRefreshing()) {
                            mPtrFrame.refreshComplete();
                        }
                    }
                }, 100);
        }
    }
    private void addHistory(){
        if (hisTagList.size()>=20){
            hisTagList.remove(hisTagList.size()-1);
        }
        hisTagList.add(0,searchContent);
        findViewById(R.id.history_lay).setVisibility(View.VISIBLE);
        if (hotTagList.size()!=0){
            findViewById(R.id.cut_line).setVisibility(View.VISIBLE);
        }else {
            findViewById(R.id.cut_line).setVisibility(View.GONE);
        }

        hisAdapter.notifyDataChanged();
        mCache.put("SEARCH_ARTICLE_HISTORY",hisTagList);
    }
    private void deleHistory(){
        hisTagList.clear();
        mCache.put("SEARCH_ARTICLE_HISTORY",hisTagList);
        hisAdapter.notifyDataChanged();
        findViewById(R.id.history_lay).setVisibility(View.GONE);
        findViewById(R.id.cut_line).setVisibility(View.GONE);
    }
    private void getHot(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        request(Contant.ARTICLE_HOT_SEARCH, params, true, false);
    }
    @Override
    public void initData() {
        getHot();
    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.ARTICLE_HOT_SEARCH)){
            if (responseInfo.isRequestOk){
                try{
                    ArticleHotTagBean hotTagBean= JSON.parseObject(responseInfo.content,ArticleHotTagBean.class);
                    if (hotTagBean!=null&&hotTagBean.getArticle_search_list()!=null&&hotTagBean.getArticle_search_list().size()>0){
                        findViewById(R.id.hot_lay).setVisibility(View.VISIBLE);
                        if (hisTagList!=null&&hisTagList.size()!=0){
                            findViewById(R.id.cut_line).setVisibility(View.VISIBLE);
                        }else {
                            findViewById(R.id.cut_line).setVisibility(View.GONE);
                        }
                        hotTagList.clear();
                        hotTagList.addAll(hotTagBean.getArticle_search_list());
                        hotAdapter.notifyDataChanged();
                    }else {
                        findViewById(R.id.hot_lay).setVisibility(View.GONE);

                    }
                }catch (Exception e){

                }
            }
        }else if (responseInfo.url.equals(Contant.ARTICLE_SEARCH)){
            if (mPtrFrame.isRefreshing()) {
                mPtrFrame.refreshComplete();
            }
            if (responseInfo.isRequestOk){
                try{
                    listBean=JSON.parseObject(responseInfo.content,ArticleListBean.class);
                    if (listBean!=null&&listBean.getArticle_list()!=null){
                        if (listBean.getArticle_list().size()>0)
                            page++;
                        for (int i = 0; i <listBean.getArticle_list().size() ; i++) {
                            if (listBean.getArticle_list().get(i).getMaster_url()==null
                                    ||listBean.getArticle_list().get(i).getMaster_url().equals("")){
                                listBean.getArticle_list().get(i).setIs_special("1");
                            }
                        }
                        articleList.addAll(listBean.getArticle_list());
                    }
                    mAdapter.notifyDataSetChanged();
                    if (articleList.size()==0){
                        loadingView.noResult();
                    }else {
                        loadingView.finish();
                    }
                }catch (Exception e){
                    if (page==1)
                        loadingView.fail();
                }
            }else {
                if (page==1)
                    loadingView.fail();
            }
        }
    }

    public void onClick(View view){
        switch (view.getId()){
            case R.id.delete_his:
                ConfirmDialog dialog=new ConfirmDialog(this, "确定删除资讯搜索记录?", new ConfirmDialog.onConfirmClickListenr() {
                    @Override
                    public void onConfirm() {
                        deleHistory();
                    }

                    @Override
                    public void onCancel() {

                    }
                });
                dialog.show();
                break;
            case R.id.clear:
                searchEd.setText("");
                break;
            case R.id.cancel:
                this.finish();
                break;
        }
    }
}
